import request from '@/utils/request';
/**
 * 数组字典
 */

const DEFAULT_KEY_CONFIG = { valueKey: 'value', textKey: 'text' };

// 缓存后台数据字典
const STORAGE_KEY = 'dictionary';
const EMPTY = [];
// 生成key值
const generateKey = (code, treeFlag) => (treeFlag ? code + treeFlag : code);
// 从 SessionStorage 中读取所有数据
const getStorage = () => {
    const dictStr = sessionStorage.getItem(STORAGE_KEY) || '{}';
    return JSON.parse(dictStr);
};
// 通过 Code 读取数据
const getStorageByCode = (code, treeFlag) => {
    if (!code) return EMPTY;
    return getStorage()[generateKey(code, treeFlag)] || EMPTY;
};
// 添加到缓存中
const setStorage = (code, value, treeFlag) => {
    if (!code) {
        return;
    }
    const dictObj = getStorage();
    dictObj[generateKey(code, treeFlag)] = value;
    sessionStorage.setItem(STORAGE_KEY, JSON.stringify(dictObj));
};

/**
 * 获取字典值的 text 值
 * value 支持字符串和数组格式
 * @param dict
 * @param value
 * @param keyConfig
 * @returns {string|*}
 */
export function getDisplayText(dict, value, keyConfig = DEFAULT_KEY_CONFIG) {
    let ret = '';
    const separate = ' ';
    const { valueKey, textKey } = { ...DEFAULT_KEY_CONFIG, ...keyConfig };
    if (!dict || !dict.length || value === '') {
        return ret;
    }
    // value为数组时，显示拼接名称
    if (Object.prototype.toString.call(value) === '[object Array]') {
        value.forEach(item => {
            const temp = getDisplayText(dict, item, { valueKey, textKey });
            ret += temp ? `${temp}${separate}` : '';
        });
        return ret;
    }
    const target = dict.find(item => item[valueKey] === value);
    ret = ((target && target[textKey]) || value) ?? ret;
    return ret;
}

/**
 * 获取字典数据
 *
 * getDict('code') => []
 * getDict('code', 0) => []
 * getDict('code', 0, { valueKey: 'value', textKey: 'text' }) => []
 *
 * @param code 字典 Code
 * @param treeFlag 是否是树的格式
 * @param keyConfig key值设定
 * @param useCache
 * @param isAuth 是否鉴权
 * @returns {Promise<Array>}
 */
export async function getDict(code, treeFlag = 0, keyConfig = DEFAULT_KEY_CONFIG, useCache = true, isAuth = true) {
    const dict = useCache ? getStorageByCode(code, treeFlag) : [];
    if (dict.length) {
        return Promise.resolve(dict);
    }
    return new Promise(resolve => {
        fetch({ codes: [code], isShowChildFormat: treeFlag, isAuth })
            .then(res => {
                const { code: resCode, data } = res;
                if (resCode !== 10000) {
                    console.error('请求后台数据字典错误~~~');
                    return resolve(EMPTY);
                }
                if (!data || !(data instanceof Array) || data.length === 0) {
                    console.warn('请后台数据字典返回为空~~~');
                    return resolve(EMPTY);
                }
                const ret = data.map(item => ({
                    ...item,
                    [keyConfig.valueKey]: item.dictValue,
                    [keyConfig.textKey]: item.dictName
                }));
                if (useCache) {
                    setStorage(code, ret, treeFlag);
                }
                return resolve(ret);
            })
            .catch(e => {
                console.error('请求后台数据字典错误~~~', e);
                resolve(EMPTY);
            });
    });
}

/**
 * 字典列表数据
 * @param {[string]} codes 字典集合
 * @param {number} isShowChildFormat 是否展示树状 1展示 0不展示
 * @param {boolean} isAuth 是否鉴权
 */
async function fetch({ codes, isShowChildFormat, isAuth }) {
    const service = isAuth ? '/api/dict/v1/getList' : '/api/dict/public/v1/getList';
    return request(service, {
        data: { codes, isShowChildFormat },
        method: 'POST'
    });
}
